package weibo4j.examples.oauth2;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import weibo4j.Oauth;
import weibo4j.http.AccessToken;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;
import weibo4j.util.WeiboConfig;

public class OAuth4Code {
	public static void main(String [] args) throws WeiboException, IOException{
		AccessToken token = getToken();
		System.out.println(token);
	}


	private static AccessToken getToken() throws WeiboException, IOException {
		Oauth oauth = new Oauth();
		BareBonesBrowserLaunch.openURL(oauth.authorize("code"));
		System.out.println(oauth.authorize("code"));
		System.out.print("Hit enter when it's done.[Enter]:");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String code = br.readLine();
		Log.logInfo("code: " + code);
		return oauth.getAccessTokenByCode(code);
	}
	
	
	public static AccessToken refreshToken() throws WeiboException{
        try {
                PostMethod postMethod = new PostMethod(WeiboConfig.getValue("authorizeURL"));
                postMethod.addParameter("client_id", WeiboConfig.getValue("client_ID").trim());//your client id
                postMethod.addParameter("redirect_uri", WeiboConfig.getValue("redirect_URI").trim());//your url
                postMethod.addParameter("response_type", "code");//code
                postMethod.addParameter("isLoginSina", "0");
                postMethod.addParameter("action", "submit");
                HttpMethodParams param = postMethod.getParams();
                param.setContentCharset("UTF-8");
                List<Header> headers = new ArrayList<Header>();
                System.out.println("https://api.weibo.com/oauth2/authorize?client_id=" + WeiboConfig.getValue("client_ID").trim() + "&redirect_uri=" + WeiboConfig.getValue("redirect_URI").trim() + "&from=sina&response_type=code");
                headers.add(new Header("Referer", "https://api.weibo.com/oauth2/authorize?client_id=" + WeiboConfig.getValue("client_ID").trim() + "&redirect_uri= " + WeiboConfig.getValue("redirect_URI").trim() + "&from=sina&response_type=code"));//伪造referer
                headers.add(new Header("Host", "api.weibo.com"));
                headers.add(new Header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));
                HttpClient client  = new HttpClient();
                client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
                client.executeMethod(postMethod);
                int status = postMethod.getStatusCode();
                if(status != 302){
                		Log.logError("refresh token failed");
                        return null;
                }
                Header location = postMethod.getResponseHeader("Location");
                if(location != null){
                        String retUrl = location.getValue();
                        int begin = retUrl.indexOf("code=");
                        if(begin != -1){
                                int end = retUrl.indexOf("&", begin);
                                if(end == -1)
                                        end = retUrl.length();
                                String code = retUrl.substring(begin+5, end);
                                if(code != null){
                                				Oauth oauth = new Oauth();
                                                AccessToken token = oauth.getAccessTokenByCode(code);
                                                return token;
                                }
                        }
                }
        } catch (FileNotFoundException e) {
        	Log.logError("error" + e);
        } catch (IOException e) {
        	Log.logError("error" + e);
        }
        Log.logError("refresh token failed");
        return null;
} 

}
